<!-- 临床病史 既往史 MedicalHistory -->
<template>
  <div class="page-center">
    <div class="medical-form">
      <el-form :model="formData" label-width="140px" class="info-form" label-position="left">
        <el-divider content-position="left">
          <h3>既往史</h3>
        </el-divider>

        <el-row :gutter="12">
          <!-- 既往史信息 -->
          <el-col :span="24">
            <el-card class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>既往病史</span>
              </div>
              <el-form-item label="手术史">
                <div class="display-value info-value">{{ display(formData.surgeryHistory) }}</div>
              </el-form-item>
              <el-form-item label="外伤史">
                <div class="display-value info-value">{{ display(formData.traumaHistory) }}</div>
              </el-form-item>
              <el-form-item label="高血压">
                <div class="display-value info-value">{{ display(formData.hypertension) }}</div>
              </el-form-item>
              <el-form-item label="心脏病">
                <div class="display-value info-value">{{ display(formData.heartDisease) }}</div>
              </el-form-item>
              <el-form-item label="糖尿病">
                <div class="display-value info-value">{{ display(formData.diabetes) }}</div>
              </el-form-item>
              <el-form-item label="肾脏疾病">
                <div class="display-value info-value">{{ display(formData.kidneyDisease) }}</div>
              </el-form-item>
              <el-form-item label="结核病">
                <div class="display-value info-value">{{ display(formData.tuberculosis) }}</div>
              </el-form-item>
              <el-form-item label="肝炎">
                <div class="display-value info-value">{{ display(formData.hepatitis) }}</div>
              </el-form-item>
              <el-form-item label="其他病史">
                <div class="display-value info-value">{{ display(formData.otherHistory) }}</div>
              </el-form-item>
            </el-card>

            <el-card class="box-card" shadow="never" style="margin-top: 16px;">
              <div slot="header" class="clearfix">
                <span>过敏史</span>
              </div>
              <el-form-item label="药物过敏">
                <div class="display-value info-value">{{ display(formData.drugAllergy) }}</div>
              </el-form-item>
              <el-form-item label="食物过敏">
                <div class="display-value info-value">{{ display(formData.foodAllergy) }}</div>
              </el-form-item>
              <el-form-item label="其他过敏">
                <div class="display-value info-value">{{ display(formData.otherAllergy) }}</div>
              </el-form-item>
            </el-card>

            <el-card class="box-card" shadow="never" style="margin-top: 16px;">
              <div slot="header" class="clearfix">
                <span>其他信息</span>
              </div>
              <el-form-item label="长期用药">
                <div class="display-value info-value">{{ display(formData.longTermMedication) }}</div>
              </el-form-item>
              <el-form-item label="输血史">
                <div class="display-value info-value">{{ display(formData.bloodTransfusion) }}</div>
              </el-form-item>
              <el-form-item label="子女数">
                <div class="display-value info-value">{{ display(formData.children) }}</div>
              </el-form-item>
              <el-form-item label="性生活史">
                <div class="display-value info-value">{{ display(formData.sexLife) }}</div>
              </el-form-item>
              <el-form-item label="家族史">
                <div class="display-value info-value medical-history-content">
                  {{ display(formData.familyHistory) }}
                </div>
              </el-form-item>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { clinical } from '@/api/dataEntry/ClinicalHistory'

export default {
  name: 'MedicalHistory',
  data() {
    return {
      formData: {
        id: 0,
        surgeryHistory: '',
        traumaHistory: '',
        hypertension: '',
        heartDisease: '',
        diabetes: '',
        kidneyDisease: '',
        tuberculosis: '',
        hepatitis: '',
        otherHistory: '',
        drugAllergy: '',
        foodAllergy: '',
        longTermMedication: '',
        otherAllergy: '',
        bloodTransfusion: '',
        children: 0,
        sexLife: '',
        familyHistory: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters('patient', ['robustPatientId', 'patientFallbackData'])
  },
  watch: {
    robustPatientId: {
      handler(newId) {
        if (newId) {
          this.loadData(newId)
        } else {
          this.resetForm()
        }
      },
      immediate: true
    }
  },
  async mounted() {
    // 如果当前没有患者信息，尝试从存储恢复
    if (!this.robustPatientId) {
      const restored = await this.restorePatientFromStorage()
      if (restored) {
        this.loadData(restored.id || restored.patientId)
      }
    }
  },
  methods: {
    ...mapActions('patient', ['restorePatientFromStorage']),

    async loadData(patientId) {
      if (this.loading) return

      this.loading = true
      try {
        const res = await clinical({ recordId: patientId })
        this.handleResponseData(res)
      } catch (error) {
        console.error('加载既往史失败:', error)
        this.applyFallbackData()
      } finally {
        this.loading = false
      }
    },

    handleResponseData(res) {
      const payload = res?.data?.data ?? res?.data ?? res ?? {}

      if (payload && Object.keys(payload).length > 0) {
        this.formData = {
          ...this.formData,
          ...payload
        }
      }
    },

    applyFallbackData() {
      const patient = this.patientFallbackData
      if (patient) {
        // 从患者数据中提取可能的既往史信息
        const medicalHistoryData = {
          surgeryHistory: patient.surgeryHistory,
          traumaHistory: patient.traumaHistory,
          hypertension: patient.hypertension,
          heartDisease: patient.heartDisease,
          diabetes: patient.diabetes,
          kidneyDisease: patient.kidneyDisease,
          tuberculosis: patient.tuberculosis,
          hepatitis: patient.hepatitis,
          otherHistory: patient.otherHistory,
          drugAllergy: patient.drugAllergy,
          foodAllergy: patient.foodAllergy,
          longTermMedication: patient.longTermMedication,
          otherAllergy: patient.otherAllergy,
          bloodTransfusion: patient.bloodTransfusion,
          children: patient.children,
          sexLife: patient.sexLife,
          familyHistory: patient.familyHistory
        }

        // 过滤掉空值，避免覆盖现有数据
        Object.keys(medicalHistoryData).forEach(key => {
          if (medicalHistoryData[key] !== undefined && medicalHistoryData[key] !== null && medicalHistoryData[key] !== '') {
            this.formData[key] = medicalHistoryData[key]
          }
        })
      }
    },

    resetForm() {
      this.formData = {
        id: 0,
        surgeryHistory: '',
        traumaHistory: '',
        hypertension: '',
        heartDisease: '',
        diabetes: '',
        kidneyDisease: '',
        tuberculosis: '',
        hepatitis: '',
        otherHistory: '',
        drugAllergy: '',
        foodAllergy: '',
        longTermMedication: '',
        otherAllergy: '',
        bloodTransfusion: '',
        children: 0,
        sexLife: '',
        familyHistory: ''
      }
    },

    display(val) {
      if (val === null || val === undefined || String(val).trim() === '') return '-'
      return val
    }
  }
}
</script>

<!-- 引入共享样式 -->
<style src="@/styles/shared.css"></style>

<style scoped>
.medical-history-content {
  white-space: pre-wrap;
  line-height: 1.6;
  min-height: 60px;
  padding: 8px 0;
}
</style>
